package com.gin.no_gay_alliance.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;

import com.bumptech.glide.Glide;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.utils.UrlUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/23 09:15
 **/
public class ContentWebViewClient extends WebViewClient {
    public static final String TAG = ContentWebViewClient.class.getSimpleName();
    final Context context;

    public ContentWebViewClient(Context context) {
        this.context = context;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        String url = request.getUrl().toString();
        // 如果本app可以打开，打开
        if (UrlUtils.isOpenableUrl(url)) {
            UrlUtils.openUrl(url, context);
            return true;
        }
        UrlUtils.openUrlWithBrowser(url, context);
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
//        Log.d(TAG, "onPageStarted: 页面开始加载，阻止加载图片");
//        view.getSettings().setBlockNetworkImage(true);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        //页面加载完毕后，开始加载图片
//        view.getSettings().setBlockNetworkImage(false);
    }

    @Nullable
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        String url = request.getUrl().toString();
        if (url.endsWith(".png") || url.endsWith(".jpg") || url.endsWith(".jpeg")) {
            try {
//                Log.d(TAG, "glide: " + url);
                Bitmap bitmap = Glide.with(context).asBitmap().load(url).submit().get();
                return new WebResourceResponse("image/png", "UTF-8", getBitmapInputStream(bitmap, Bitmap.CompressFormat.PNG));
            } catch (Exception e) {
                e.printStackTrace();
                Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_broken_image_24, context.getTheme());
                if (drawable == null) {
                    return new WebResourceResponse("text/html", "UTF-8", null);
                }
                Bitmap bitmap = drawableToBitmap(drawable);
                return new WebResourceResponse("text/html", "UTF-8", getBitmapInputStream(bitmap, Bitmap.CompressFormat.PNG));
            }
        } else if (url.startsWith("http")) {
            Log.d(TAG, "shouldInterceptRequest: " + url);
        }

        return super.shouldInterceptRequest(view, request);
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {

        Bitmap bitmap = Bitmap
                .createBitmap(
                        drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight(),
                        drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    private static InputStream getBitmapInputStream(Bitmap bitmap, Bitmap.CompressFormat format) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(format, 100, byteArrayOutputStream);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        return new ByteArrayInputStream(bytes);
    }

}
